/**
 * @description koa-webpack-dev
 *
 */

const webpackDevMW = require('webpack-dev-middleware');

const middleware = function middleware(doIt, req, res) {
    const originalEnd = res.end;

    return function(done) {
        res.end = function() {
            originalEnd.apply(this, arguments);
            done(null, 0);
        };

        doIt(req, res, () => {
            done(null, 1);
        });
    };
};

module.exports = function(compiler, options) {
    const doIt = webpackDevMW(compiler, options);
    const mw = function *(next) {
        const ctx = this;
        const req = this.req;

        const runNext = yield middleware(doIt, req, {
            end(content) {
                ctx.body = content;
            },
            setHeader() {
                ctx.set.apply(ctx, arguments);
            }
        });

        ctx.webpack = doIt;

        if(runNext && next) {
            yield next;
        }
    };

    // methods
    mw.getFilenameFromUrl = doIt.getFilenameFromUrl;
    mw.fileSystem = doIt.fileSystem;

    return mw;
};
